<template>
	<div>
		<div class="container">
			<h2 style="text-align: center;">机械签证</h2>
			<div class="toolbar mt-2">
				<a-form ref="searchRef" layout="inline" :label-col="{style: { width: '120px' }}" :model="searchState" @finish="current=1;loading=true;initData()">
					<a-row :gutter="20">
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="城市公司/专业公司">
								<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label" allow-clear @change="changeProject"></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="选择供应商名称" name="supplier_id">
								<a-select v-model:value="searchState.supplier_id" :show-search="true" placeholder="请选择供应商" :options="userlist" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="发货单编号" name="code">
								<a-input v-model:value="searchState.code" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="验收单编号">
								<a-input v-model:value="searchState.ys_code" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="状态" name="visa_status">
								<a-select v-model:value="searchState.visa_status" :show-search="true" placeholder="请选择状态" :options="statusOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="时间范围">
								<a-range-picker v-model:value="searchState.date_range" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
							</a-form-item>
						</a-col>
						<a-col :span="8" style="padding: 15px 0;">
							<a-radio-group v-model:value="searchState.date_type" style="margin-left: 20px;" @change="setDatetype">
								<a-radio :value="1">上周</a-radio>
								<a-radio :value="2">上月</a-radio>
								<a-radio :value="3">本周</a-radio>
								<a-radio :value="4">本月</a-radio>
							</a-radio-group>
						</a-col>
						<a-col :span="8" style="padding: 10px 0;">
							<a-form-item label="选择验收人" name="ys_opr_id">
								<a-select v-model:value="searchState.ys_opr_id" :show-search="true" placeholder="请选择验收人" :options="oprlist" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="4">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>
								</a-space>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<!--
        v-if="!loading"使得:default-expand-all-rows="true"生效
        -->
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="yanshouSource" :pagination="pagination" :loading="loading" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'visa_status'">
							<tempalte v-if="record.materials?.[0]?.unit === '台/月'">
								<a-button v-if="record.visaLogs?.find(item => dayjs(item.visa_date).format('YYYY-MM') === dayjs().format('YYYY-MM'))" v-permission:show="232" @click="show(record)">查看</a-button>
								<a-typography-text v-else disabled>暂无</a-typography-text>
							</tempalte>
							<tempalte v-else>
								<a-button v-if="record.visaLogs?.length" v-permission:show="232" @click="show(record)">查看</a-button>
								<a-typography-text v-else disabled>暂无</a-typography-text>
							</tempalte>
						</template>
						<template v-if="column.key === 'operation'">
							<template v-if="record.materials?.[0]?.unit === '台/月'">
								<a-space v-if="!record.visaLogs?.find(item => dayjs(item.visa_date).format('YYYY-MM') === dayjs().format('YYYY-MM'))">
									<a-button v-permission:show="223" @click="edit(record)">
										待签证
									</a-button>
								</a-space>
								<a-space v-else-if="record.visaLogs?.find(item => dayjs(item.visa_date).format('YYYY-MM') === dayjs().format('YYYY-MM')).visa_status === 3">
									<a-button v-permission:show="223" type="primary" @click="edit(record)">
										已签证
									</a-button>
								</a-space>
								<a-space v-else>
									<a-button v-permission:show="223" @click="edit(record)">
										签证中
									</a-button>
								</a-space>
							</template>
							<template v-else>
								<a-space v-if="!record.visaLogs?.length">
									<a-button v-permission:show="223" @click="edit(record)">
										待签证
									</a-button>
								</a-space>
								<a-space v-else-if="record.visaLogs[0].visa_status === 3">
									<a-button v-permission:show="223" type="primary" @click="edit(record)">
										已签证
									</a-button>
								</a-space>
								<a-space v-else>
									<a-button v-permission:show="223" @click="edit(record)">
										签证中
									</a-button>
								</a-space>
							</template>
						</template>
					</template>
					<template #expandedRowRender="{record}">
						<a-table :columns="innerColumns" :data-source="innerRecord(record?.visaLogs)" :pagination="false">
							<template #bodyCell="{ column, record: rd }">
								<template v-if="column.dataIndex === 'visa_status'">
									<a-space>
										<a-button v-permission:show="232" @click="show({id: rd.supply_order_id}, rd.batch)">
											查看
										</a-button>
									</a-space>
								</template>
								<template v-if="column.key === 'operation'">
									<a-space>
										<a-button v-if="rd.visa_status === 3" v-permission:show="223" type="primary" @click="edit({id: rd.supply_order_id}, rd.batch)">
											已签证
										</a-button>
										<a-button v-else v-permission:show="223" @click="edit({id: rd.supply_order_id}, rd.batch)">
											签证中
										</a-button>
									</a-space>
								</template>
							</template>
						</a-table>
					</template>
				</a-table>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance } from "vue";
import { useRouter, useRoute } from "vue-router";
import { cloneDeep } from 'lodash-es';
const { proxy } = getCurrentInstance();
import dayjs from "dayjs";

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, RightOutlined } from "@ant-design/icons-vue";

import { post, postJson } from "../utils";

import { usePagination } from "vue-request";
import { userStore } from "@/store/index.js";
import { add } from "../utils/operation.js";

const store = userStore();
const userInfo = store.info;
const searchRef = ref();
const searchState = reactive({});
const projectOptions = ref([]);
const companyOptions = ref([]);
const planlist = ref([]);
const contractlist = ref([]);
const userlist = ref([]); //供应商列表
const oprlist = ref([]); //操作人列表
const router = useRouter();
const route = useRoute();
const query = route.query;
const statusOptions = [
	{
		value: -1,
		label: "待签证"
	},
	{
		value: 0,
		label: "签证中"
	},
	{
		value: 1,
		label: "已签证"
	}
];

const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 100,
		align: "left",
		fixed: "left"
	},
	{
		title: "项目名称",
		dataIndex: "project",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return text.name;
		}
	},
	{
		title: "供应商名称",
		dataIndex: "supplier",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return text.company_name;
		}
	},
	{
		title: "发货单编号",
		dataIndex: "code",
		sorter: false,
		width: 150,
		ellipsis: true,
	},
	{
		title: "验收单号",
		dataIndex: "yanshoulogs",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text?.[0].code;
		}
	},
	{
		title: "验收人",
		dataIndex: "ys_settings",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text?.find(item => item.opr_type === 1)?.opr.fullname ||
          record.yanshoulogs?.[0].opr.fullname || record.yanshoulogs?.[0].opr.fullname.username
		}
	},
	{
		title: "进场时间",
		dataIndex: "yanshoulogs",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text?.[0]?.create_time).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "机械名称",
		dataIndex: "materials",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text?.[0]?.name;
		}
	},
	{
		title: "规格型号",
		dataIndex: "materials",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text?.[0]?.model;
		}
	},
	{
		title: "计量单位",
		dataIndex: "materials",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text?.[0]?.unit;
		}
	},
	{
		title: "使用时长",
		dataIndex: "visaLogs",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text?.filter(item => dayjs(item.visa_date).format("YYYY-MM") === dayjs().format("YYYY-MM"))?.reduce((target, item) => {
				return add([target, item.work_hours]);
			}, 0) || '确认中';
		}
	},
	{
		title: "签证",
		dataIndex: "visa_status",
		width: 150,
		align: "center"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 300,
		align: "center"
	}
];
const innerColumns = [
	{
		title: "签证编号",
		dataIndex: "code",
		ellipsis: true
	},
	{
		title: "签证时间",
		dataIndex: "create_time",
		ellipsis: true
	},
	{
		title: "签证人",
		dataIndex: "opr",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text?.fullname || text?.username;
		}
	},
	{
		title: "签证时长",
		dataIndex: "work_hours",
		align: "center",
	},
	{
		title: "签证",
		dataIndex: "visa_status",
		align: "center",
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 300,
		align: "center"
	},
];
const innerRecord = (visaLogs) => {
	const map = {};
	for (const item of visaLogs) {
		if (!map[item.batch]) {
			map[item.batch] = cloneDeep(item);
			continue;
		}
		map[item.batch].work_hours = add([item.work_hours, map[item.batch].work_hours])
	}
	return Object.values(map);
}
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const getProjects = async () => {
	const projectResult = await post("department/projects?type=3", { page_size: 1000 });
	projectOptions.value = projectResult.data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
};
if (!projectOptions.value.length) {
	getProjects();
}
const { data, loading, run, current, pageSize, total } = usePagination(async params => {
	const search = {
		ys_type: 4,
	};
	if (searchState.company_id) {
		if (!projectOptions.value.length) await getProjects();
		search.project_ids = projectOptions.value
			.filter(item => {
				return item.parseIds.includes(searchState.company_id);
			})
			.map(item => item.value);
		if (!search.project_ids) {
			return [];
		}
	}
	return postJson("visa", { ...params, ...searchState, ...search });
},
{
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
}
);

const yanshouSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);
const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	let query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	query = {
		...query,
		...filters,
		start_time: searchState.date_range && dayjs(searchState.date_range[0]).format('YYYY-MM-DD'),
		end_time: searchState.date_range && dayjs(searchState.date_range[1]).format('YYYY-MM-DD'),
	}
	delete query.date_range;
	router.replace({ query })
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.supplier_id) searchState.supplier_id = parseInt(query.supplier_id);
	if (query.code) searchState.code = query.code;
	if (query.ys_code) searchState.ys_code = query.ys_code;
	if (query.visa_status) searchState.visa_status = parseInt(query.visa_status);
	if (query.start_time && query.end_time) {
		searchState.date_range = [
			dayjs(query.start_time).format('YYYY-MM-DD HH:mm:ss'),
			dayjs(query.end_time).format('YYYY-MM-DD HH:mm:ss')
		];
	}
	console.log('query', query)
	console.log('searchState', searchState)
	if (query.ys_opr_id) searchState.ys_opr_id = parseInt(query.ys_opr_id);
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectOptions.value.length) return options;
	if (searchState.company_id) {
		options = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		})
	} else {
		options = projectOptions.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		console.log(1111111)
		searchState.project_id = null;
	}
	return options;
})
post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24])
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("plan", { type: 1, page_size: Infinity }).then(({ data }) => {
	planlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("contract", { type: 1 }).then(({ data }) => {
	contractlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("user", { is_supplier: 1, page_size: Infinity }).then(({ data }) => {
	userlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.company_name
		};
	});
});
post("user", { page_size: Infinity }).then(({ data }) => {
	oprlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.fullname
		};
	});
});
const changeProject = value => {
	const project_id = value;
	post("plan", { type: 1, project_id: project_id, page_size: 1000 }).then(({ data }) => {
		planlist.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
	});
};

const setDatetype = () => {
	switch (searchState.date_type) {
	// 上周
	case 1:
		searchState.date_range = [
			dayjs().startOf("week").subtract(1, "week").format("YYYY-MM-DD"),
			dayjs().endOf("week").subtract(1, "week").format("YYYY-MM-DD")
		];
		break;
		// 上月
	case 2:
		searchState.date_range = [
			dayjs().startOf("month").subtract(1, "month").format("YYYY-MM-DD"),
			dayjs().endOf("month").subtract(1, "month").format("YYYY-MM-DD")
		];
		break;
		// 本周
	case 3:
		searchState.date_range = [
			dayjs().startOf("week").format("YYYY-MM-DD"),
			dayjs().endOf("week").format("YYYY-MM-DD")
		];
		break;
		// 本月
	case 4:
		searchState.date_range = [
			dayjs().startOf("month").format("YYYY-MM-DD"),
			dayjs().endOf("month").format("YYYY-MM-DD")
		];
		break;
	}
}
const show = (record, batch) => {
	const id = record.id;
	const query = {};
	if (batch) {
		query.batch = batch;
	}
	router.push({
		path: `/yanshou/visajx/info/${id}`,
		query
	});
};
const edit = (record, batch) => {
	const id = record.id;
	const query = {};
	if (batch) {
		query.batch = batch;
	}
	router.push({
		path: `/yanshou/visajx/edit/${id}`,
		query
	});
};
</script>
<style scoped lang="scss">
.container {
  background: #fff;
  padding: 12px;
}
:deep(.ant-table-expanded-row-fixed) {
  padding-right: 0;
}
</style>
